/*
 *
 * Copyright (c) 2020 The Raptor Authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#ifndef RAPTOR_LITE_SRC_WINDOWS_CONTAINER_H_
#define RAPTOR_LITE_SRC_WINDOWS_CONTAINER_H_

#include <time.h>
#include <map>
#include <memory>
#include <list>
#include <utility>
#include <vector>

#include "raptor-lite/impl/container.h"
#include "raptor-lite/impl/handler.h"
#include "raptor-lite/utils/timer.h"

#include "src/common/common.h"
#include "src/common/mini_container.h"

namespace raptor {

class PollingThread;

struct ContainerMessageNode;
class ContainerImpl : public Container,
                      public TimerHandler,
                      public internal::EventReceivingService,
                      public internal::NotificationTransferService {
public:
    explicit ContainerImpl(Option *option);
    ~ContainerImpl();

    raptor_error Init(PollingThread *pt);
    raptor_error Start() override;
    void Shutdown() override;
    raptor_error AttachEndpoint(Endpoint ep) override;
    bool SendMsg(uint32_t connection_id, const Slice &s) override;
    void CloseEndpoint(Endpoint ep, bool notify = false) override;

    // internal::EventReceivingService implement
    void OnEventProcess(EventDetail *detail) override;

    // internal::NotificationTransferService impl
    void OnDataReceived(Endpoint ep, const Slice &s) override;
    void OnClosed(Endpoint ep, raptor_error desc) override;
    void OnHeartBeat(Endpoint ep) override;

private:
    void MessageQueueThread(void *);
    void Dispatch(struct ContainerMessageNode *msg);
    void OnTimer(uint32_t tid1, uint32_t tid2) override;

    MiniContainer *FindMiniContainer();

private:
    bool shutdown_;
    uint16_t magic_number_;

    Option option_;
    Thread thd_;

    AtomicInt64 count_;
    Mutex cmtx_;
    ConditionVariable cv_;
    MultiProducerSingleConsumerQueue mpscq_;

    std::vector<MiniContainer *> mgr_;

    PollingThread *polling_thread_;

    std::shared_ptr<Timer> timer_thread_;
};

} // namespace raptor
#endif // RAPTOR_LITE_SRC_WINDOWS_CONTAINER_H_
